package com.headFirstModel.iteratorPattern;

import java.util.Iterator;

/**
 * 餐厅菜单实现
 */
public class DineMenu implements Menu{
    //菜单最多保存六个菜品
    static final int MAX_ITEMS=6;
    int numberOfItems=0;
    MenuItem[] menuItems;

    public DineMenu(){
        menuItems=new MenuItem[MAX_ITEMS];
        addItem("酸辣鸡杂","酸豆角+鸡杂，美味...",false,5.22);
        addItem("红烧土豆片","油炸，爽口，美味...",true,2.22);
        addItem("红烧鱼","外焦里嫩，美味...",false,7.22);
    }
    private void addItem(String name, String description, boolean vegetarian, double price) {
        MenuItem menuItem=new MenuItem(name,description,vegetarian,price);
        if(numberOfItems>=MAX_ITEMS){
            System.out.println("菜单已满，无法添加...");
        }else{
            menuItems[numberOfItems++]=new MenuItem(name,description,vegetarian,price);
        }
    }

    public MenuItem[] getMenuItems() {
        return menuItems;
    }

    public Iterator<MenuItem> createIterator() {
        return  new DineMenuIterator();
    }
    //菜单的其他方法.....

    //实现迭代器
    final class DineMenuIterator implements Iterator<MenuItem>{
        MenuItem[] items;
        int position=0; //指针的作用

        public DineMenuIterator(){
            //需要迭代的对象
            this.items=menuItems;
        }

        @Override
        public boolean hasNext() {
            if(position>=items.length||items[position]==null){
                return  false;
            }else{
                return  true;
            }
        }

        @Override
        //返回当前对象并将指针指向下一位
        public MenuItem next() {
           MenuItem menuItem=items[position];
           position++;
           return  menuItem;
        }

        public void remove(){
            if(position<=0){
                throw new UnsupportedOperationException("you can not romove" +
                        "an item until you have done at least one next()");
            }
            if(items[position-1]!=null){
                for (int i=position-1;i<(items.length-1);i++){
                    items[i]=items[i+1];
                }
                items[items.length-1]=null;
            }
        }
    }
}
